// 实现这个项目的构建任务
const { series, parallel, watch } = require("gulp");
const { src, dest } = require("gulp");
const del = require("del");
const loadPlugins = require("gulp-load-plugins");
const plugins = loadPlugins();
const brosweSync = require("browser-sync");
const browserSync = require("browser-sync");
const serve = browserSync.create();

const data = {
  pkg: require("./package.json"),
  date: new Date(),
};
const clean = () => {
  return del(["dist"]);
};

const style = () => {
  return src("src/assets/styles/*.scss", { base: "src" })
    .pipe(plugins.sass({ outputStyle: "expanded" }))
    .pipe(dest("dist"));
};

const script = () => {
  return src("src/assets/scripts/*.js", { base: "src" })
    .pipe(plugins.babel({ presets: ["@babel/preset-env"] }))
    .pipe(dest("dist"));
};

const page = () => {
  return src("src/*.html", { base: "src" })
    .pipe(plugins.swig({ data }))
    .pipe(dest("dist"));
};

// const image = () => {
//     return src('src/assets/images/**', {base: 'src'})
//     .pipe(plugins.imagemin())
//     .pipe(dest('dist'))
// }

// const font = () => {
//     return src('src/assets/fonts/**', {base: 'src'})
//     .pipe(plugins.imagemin())
//     .pipe(dest('dist'))
// }

const extra = () => {
  return src("public/**", { base: "public" }).pipe(dest("dist"));
};

const server = () => {
  watch("src/assets/styles/*.scss", style);
  watch("src/assets/scripts/*.js", script);
  watch("src/*.html", page);
  watch(
    ["src/assets/images/**", "public/**", "src/assets/fonts/**"],
    serve.reload
  );
  serve.init({
    notify: false,
    port: 7080,
    files: "dist/**",
    server: {
      // 这样设置就可以在src下寻找开发阶段不需要的图片等构建
      baseDir: ["dist", "src"],
      routes: {
        "/node_modules": "node_modules",
      },
    },
  });
};

const compile = parallel(style, script, page);
const build = parallel(compile, extra);
const dev = series(compile, server);
const start = series(compile, server);

module.exports = {
  clean,
  compile,
  build,
  server,
  dev,
  start,
};
